package com.ewing.extranal.im;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.http.HttpSession;
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

/**
 * 类/接口注释
 * 
 * @author tansonlam
 * @createDate 2016年4月21日
 * 
 */
//@ServerEndpoint(value = "/websocket/chat", configurator = GetHttpSessionConfigurator.class)
public class SimpleChat {

    private static Logger logger = Logger.getLogger(SimpleChat.class);

    private static final ConcurrentHashMap<Integer, SimpleChat> connections = new ConcurrentHashMap<Integer, SimpleChat>();

    private Integer imUserId;
    private Session session;;
    private HttpSession httpSession;

    public SimpleChat() {

    }

    @OnOpen
    public void start(Session session, EndpointConfig config) {
        this.session = session;

        this.httpSession = (HttpSession) config.getUserProperties()
                .get(HttpSession.class.getName());
        if (this.httpSession == null)
            return;
        this.imUserId = (Integer) httpSession.getAttribute("imUserId");
        if (this.imUserId != null)
            connections.put(imUserId, this);
    }

    @OnClose
    public void end() {
        connections.remove(imUserId);
    }

    @OnMessage
    public void incoming(String recMessage, EndpointConfig config) {
        String[] recMessageArr =  StringUtils.split(recMessage,"|@|");
        if (recMessageArr.length != 2)
            return;
        Integer sendUserId = Integer.valueOf(recMessageArr[0]);
        String sendMessage = recMessageArr[1];
        sendMessage(sendUserId, sendMessage);
    }

    @OnError
    public void onError(Throwable t) throws Throwable {
        logger.error("Chat Error: " + t.toString(), t);
    }

    private static void sendMessage(Integer imUserId, String msg) {
        SimpleChat client = null;
        try {
            client = connections.get(imUserId);
            if (client == null)
                throw new IOException("not found imUserId:" + imUserId);
            synchronized (client) {
                client.session.getBasicRemote().sendText(msg);
            }
        } catch (IOException e) {
            logger.debug("Chat Error: Failed to send message to client", e);
            connections.remove(imUserId);
            if (client != null) {
                try {
                    client.session.close();
                } catch (IOException e1) {
                    // Ignore
                }
            }
        }

    }
}
